package com.erp.gather.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.gather.domain.*;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IAeProductPostErrorService;
import com.erp.gather.service.IAeProductService;
import com.erp.gather.service.IErpUsdExchangeService;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.ae.api.domain.AeProductPost;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.ae.api.domain.ImageBankParam;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpowerExtend;
import com.ruoyi.shop.api.domain.ErpSellerStoreFreightTemplate;
import com.ruoyi.shop.api.domain.ErpSellerStoreSubcategory;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@RequiredArgsConstructor
@Service
public class AeProductServiceImpl implements IAeProductService {
    @Autowired
    RestTemplate restTemplate;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    RemoteCollectProductService remoteCollectProductService;
    @Resource
    IAeProductPostErrorService iAeProductPostErrorService;

    private final ErpProductAutoTestStoreMapper erpProductAutoTestStoreMapper;
    private final ErpSellerStoreEuResponsiblePersonMapper erpSellerStoreEuResponsiblePersonMapper;
    private final ErpSellerStoreProductSkuMapper erpSellerStoreProductSkuMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    private final IErpUsdExchangeService iErpUsdExchangeService;
    private final ErpCollectProductMapper erpCollectProductMapper;
    private final ErpCollectProductCategoryMapper erpCollectProductCategoryMapper;


    @Override
    public String getEUResponsiblePersonByCategoryId(Long categoryId, Long sellerStoreId, Integer type) {
        // sellerStoreId为当前登录账号id

        // 判断该店铺是否存在并已授权
        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(sellerStoreId);
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreEmpower erpSellerStoreEmpower = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
        if (erpSellerStoreEmpower == null || erpSellerStoreEmpower.getIsEmpower().equals("0")) {
            return null;
        }
        // 获取该店铺该类目下的信息是否存在
        if (type == 1) {
            //测试正常
            ErpSellerStoreEuResponsiblePerson erpSellerStoreEuResponsiblePerson = erpSellerStoreEuResponsiblePersonMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerStoreEuResponsiblePerson>()
                            .eq(ErpSellerStoreEuResponsiblePerson::getCategoryId, categoryId)
                            .eq(ErpSellerStoreEuResponsiblePerson::getSellerStoreId, sellerStoreId)
                            .last("limit 1"));
            if (erpSellerStoreEuResponsiblePerson != null) {
                // 若存在，返回该值
                return erpSellerStoreEuResponsiblePerson.getMsrEuId().toString();
            } else {
                // 若不存在，调用AE接口，该类目下的欧盟负责人

                return getEUResponsiblePersonFromAe(categoryId, sellerStoreId);
            }
        } else {
            return getEUResponsiblePersonFromAe(categoryId, sellerStoreId);
        }

    }

    @Override
    @Transactional
    public Integer getAllPicByProductTest(Long productId) {
        R<Object> objectR = remoteSellerStoreProductService.getSellerStoreProductInfoById(
                productId.toString());
        ErpSellerStoreProduct sellerStoreProduct = (ErpSellerStoreProduct) objectR.getData();
        if (sellerStoreProduct == null) {
            return -1;
        }
        Long storeId = sellerStoreProduct.getStoreId();
        R<Object> objectRTwo = remoteSellerStoreService.getSellerStoreInfoById(storeId);
        ErpSellerStoreEmpower storeEmpower = (ErpSellerStoreEmpower) objectRTwo.getData();
        String storeUserName = storeEmpower.getStoreUserName();
        List<ImageBankParam> bankParamList = new ArrayList<>();
        // 1.查询商品的所有图片
        // 主图
        String imageURLs = sellerStoreProduct.getImageURLs();
        if (StringUtils.isNotEmpty(imageURLs)) {
            List<String> imageURLList = ListUtil.toList(imageURLs.split(";"));
            for (String s : imageURLList) {
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setProductId(productId);
                bankParam.setImageUrl(s);
                bankParam.setType(0);
                bankParam.setGroupId("0");
                bankParam.setSellerId(storeId);
                bankParam.setStoreUserName(storeUserName);
                bankParamList.add(bankParam);
            }
        }
        // 白底图
        String white = sellerStoreProduct.getWhite();
        if (StringUtils.isNotEmpty(white)) {
            List<String> whiteList = ListUtil.toList(white.split(";"));
            for (String s : whiteList) {
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setProductId(productId);
                bankParam.setImageUrl(s);
                bankParam.setType(1);
                bankParam.setGroupId("0");
                bankParam.setStoreUserName(storeUserName);
                bankParamList.add(bankParam);
            }
        }
        // 营销图
        String marketing = sellerStoreProduct.getMarketing();
        if (StringUtils.isNotEmpty(marketing)) {
            List<String> markList = ListUtil.toList(marketing.split(";"));
            for (String s : markList) {
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setProductId(productId);
                bankParam.setImageUrl(s);
                bankParam.setType(2);
                bankParam.setGroupId("0");
                bankParam.setSellerId(storeId);
                bankParam.setStoreUserName(storeUserName);
                bankParamList.add(bankParam);
            }
        }
        // 详情图
        String detailImg = sellerStoreProduct.getDetailImg();
        if (StringUtils.isNotEmpty(detailImg)) {
            List<String> detailImgList = ListUtil.toList(detailImg.split(";"));
            for (String s : detailImgList) {
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setProductId(productId);
                bankParam.setImageUrl(s);
                bankParam.setType(3);
                bankParam.setGroupId("0");
                bankParam.setSellerId(storeId);
                bankParam.setStoreUserName(storeUserName);
                bankParamList.add(bankParam);
            }
        }
        // sku图集
        List<ErpSellerStoreProductSku> sellerStoreProductSkuList = erpSellerStoreProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
                        .eq(ErpSellerStoreProductSku::getSellerStoreProductId, productId));
        for (ErpSellerStoreProductSku sku : sellerStoreProductSkuList) {
            // sku主图
            String skuImage = sku.getSkuImage();
            if (StringUtils.isNotEmpty(skuImage)) {
                List<String> skuImageList = ListUtil.toList(skuImage.split(";"));
                for (String s : skuImageList) {
                    ImageBankParam bankParam = new ImageBankParam();
                    bankParam.setProductId(sku.getId());
                    bankParam.setImageUrl(s);
                    bankParam.setType(4);
                    bankParam.setGroupId("0");
                    bankParam.setSellerId(storeId);
                    bankParam.setStoreUserName(storeUserName);
                    bankParamList.add(bankParam);
                }
            }
        }
        // 2. 将图片传给ae,获取返回的新图
        Map<String, Object> map = new HashMap<>();
        RestTemplate restTemplate = new RestTemplate();
        String body = null;
        ResponseEntity<String> forEntity = null;
        List<ImageBankParam> returnList = new ArrayList<>();
        for (ImageBankParam imageBankParam : bankParamList) {
            R<Object> objectR1 = remoteAeProductService.uploadImageForSDKTest(imageBankParam);
            body = (String) objectR1.getData();
//            forEntity = restTemplate
//                    .postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/uploadImageForSDKTest", imageBankParam, String.class);
//            body = (String) forEntity.getBody();
            System.out.println(body);
            ImageBankParam imageBankParam1 = JSONObject.parseObject(body, ImageBankParam.class);
            returnList.add(imageBankParam1);
        }

//        List<ImageBankParam> reBankParamList = JSONArray.parseArray(body, ImageBankParam.class);

        for (ImageBankParam imageBankParam : returnList) {
            Long id = imageBankParam.getProductId();
            String newDraw = imageBankParam.getNewDraw();
            String imageUrl = imageBankParam.getImageUrl();
            Integer type = imageBankParam.getType(); // type=4,id表示sku表的主键,其余表示商品表主键
            if (newDraw == null) {
                switch (type) {
                    case 0:
                        return 0;
                    case 1:
                        return 1;
                    case 2:
                        return 2;
                    case 3:
                        return 3;
                }
            }
            if (newDraw.equals("continue")) {
                continue;
            }
            switch (type) {
                case 0:
                    imageURLs = imageURLs.replace(imageUrl, newDraw);
                    break;
                case 1:
                    white = white.replace(imageUrl, newDraw);
                    break;
                case 2:
                    marketing = marketing.replace(imageUrl, newDraw);
                    break;
                case 3:
                    detailImg = detailImg.replace(imageUrl, newDraw);
                    break;
                case 4:
                    ErpSellerStoreProductSku sku = erpSellerStoreProductSkuMapper.selectById(id);
                    // 获取skuproperty
                    sku.setSkuProperty(sku.getSkuProperty().replace(sku.getSkuImage(), newDraw));
                    sku.setSkuImage(newDraw);
                    erpSellerStoreProductSkuMapper.updateById(sku);
                    break;
            }
        }
        sellerStoreProduct.setImageURLs(imageURLs);
        sellerStoreProduct.setMarketing(marketing);
        sellerStoreProduct.setDetailImg(detailImg);
        sellerStoreProduct.setWhite(white);
        erpSellerStoreProductMapper.updateById(sellerStoreProduct);
        return 4;
    }

    @Override
    public Long getCategoryTreeListForStore(Long categoryId) {
        //获取当前类目的上级类目
        ErpCollectProductCategory erpCollectProductCategory = erpCollectProductCategoryMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductCategory>()
                        .eq(ErpCollectProductCategory::getId, categoryId)
        );
        Long parentCategoryId = erpCollectProductCategory.getParentId();
        //获取系统内当前已授权的店铺
        R<Object> storeEmpowerObject = remoteSellerStoreService.getEmpowerStore();
        String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
        List<ErpSellerStoreEmpower> erpSellerStoreEmpowerList = JSONArray.parseArray(storeEmpowerString, ErpSellerStoreEmpower.class);
//        List<ErpSellerStoreEmpower> erpSellerStoreEmpowerList = remoteSellerStoreService.getEmpowerStore();
//        List<ErpSellerStoreEmpower> erpSellerStoreEmpowerList = erpSellerStoreEmpowerMapper.getIsEmpowerStore();
        ResponseEntity<String> forEntity = null;
        String body = null;
        Long storeId = null;
        for (ErpSellerStoreEmpower store : erpSellerStoreEmpowerList) {
            //访问接口，获取该店铺有无权限
            R<Object> objectR = remoteAeProductService.categoryTreeListInnerAuth(parentCategoryId, store.getId());
            body = (String) objectR.getData();
//            forEntity = restTemplate
//                    .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/categoryTreeList?categoryId=" + parentCategoryId + "&sellerId=" + store.getId(), String.class);
//            body = (String) forEntity.getBody();
            if (body.contains(categoryId.toString())) {
                storeId = store.getId();
                break;
            }
        }
        if (storeId != null) {
            return storeId;
        } else {
            return 0L;
        }
    }

    @Override
    public R<Object> createProductAutoTestStore(Long storeId) {
        //访问接口，获取该店铺有无权限
//        forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/categoryTreeList?categoryId=" + "0" + "&sellerId=" + storeId, String.class);
        R<Object> objectOne = remoteAeProductService.categoryTreeListInnerAuth(0L, storeId);
        String body = (String) objectOne.getData();
        String string = JSONObject.parseObject(body)
                .getJSONObject("aliexpress_category_tree_list_response")
                .getJSONObject("aeop_post_category_list")
                .getString("aeop_post_category");
//        Dict parseMap = JsonUtils.parseMap(body);
        JSONArray jsonArray = JSONArray.parseArray(string);
        ErpProductAutoTestStore erpProductAutoTestStore = new ErpProductAutoTestStore();
        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(storeId);
        ErpSellerStoreEmpower store = (ErpSellerStoreEmpower) objectR.getData();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            erpProductAutoTestStore.setStoreUserName(store.getStoreUserName());
            erpProductAutoTestStore.setSellerStoreEmpowerId(storeId);
            erpProductAutoTestStore.setStatus(1);
            erpProductAutoTestStore.setCategoryId(jsonObject.getLong("id"));
            erpProductAutoTestStoreMapper.insert(erpProductAutoTestStore);
            erpProductAutoTestStore = new ErpProductAutoTestStore();
        }

        //更新该店铺运费模板
        //TODO 运费模版内部类调用
//        getSellerStoreFreightTemplate(storeId);
        //更新该店铺服务模板
        //TODO 服务模版内部类调用
//        queryPromiseTemplateById(0, storeId);


        return R.ok();
    }

    //调用AE接口获取该类目下的欧盟负责人
    public String getEUResponsiblePersonFromAe(Long categoryId, Long sellerStoreId) {
        R<Object> objectR = remoteAeProductService.getEUResponsiblePersonFromAeInnerAuth(categoryId, sellerStoreId);
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/getEUResponsiblePersonFromAe?categoryId="
//                        + categoryId + "&sellerId=" + sellerStoreId, String.class);
//        String body = (String) forEntity.getBody();
        String body = JSONObject.toJSONString(objectR.getData());
        Dict dict = JsonUtils.parseMap(body);
        if (Integer.valueOf(dict.get("code").toString()) == 500) {
            return null;
        }
        // 存储数据
        ErpSellerStoreEuResponsiblePerson erpSellerStoreEuResponsiblePerson =
                erpSellerStoreEuResponsiblePersonMapper.selectOne(
                        new LambdaQueryWrapper<ErpSellerStoreEuResponsiblePerson>()
                                .eq(ErpSellerStoreEuResponsiblePerson::getSellerStoreId, sellerStoreId)
                                .eq(ErpSellerStoreEuResponsiblePerson::getCategoryId, categoryId)
                );
        if (erpSellerStoreEuResponsiblePerson == null) {
            erpSellerStoreEuResponsiblePerson = new ErpSellerStoreEuResponsiblePerson();
        }
        erpSellerStoreEuResponsiblePerson.setSellerStoreId(sellerStoreId);
        erpSellerStoreEuResponsiblePerson.setCategoryId(categoryId);
        erpSellerStoreEuResponsiblePerson.setSupport(dict.get("support").toString());
        Boolean flag = false;
        if (erpSellerStoreEuResponsiblePerson.getSupport().equals("true")) {
            erpSellerStoreEuResponsiblePerson.setMsrEuId(Long.valueOf(dict.get("msr_eu_id").toString()));
            erpSellerStoreEuResponsiblePerson.setName(dict.get("name").toString());
            flag = true;
        } else {
            erpSellerStoreEuResponsiblePerson.setMsrEuId(Long.valueOf(-2));
            erpSellerStoreEuResponsiblePerson.setName("暂无欧盟负责人");
        }
        if (erpSellerStoreEuResponsiblePersonMapper.insertOrUpdate(erpSellerStoreEuResponsiblePerson)) {
            if (flag) {
                return erpSellerStoreEuResponsiblePerson.getMsrEuId().toString();
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public R<Object> productOfflineOrOnline(String sellerStoreProductIds, Long sellerId, Integer type) {
        Map<String, Object> returnMap = new HashMap<>();
//        if (StringUtils.isEmpty(checkSellerId(sellerId))) {
//            return R.ok("店铺未授权");
//        }
//        //确认该商品是否存在
//        ErpSellerStoreProductVo erpSellerProduct = iErpSellerStoreProductService.queryById(sellerStoreProductId);
//        if (erpSellerProduct == null) {
//            return R.ok("商品不存在");
//        }
        ResponseEntity<String> forEntity = null;
        String body = null;
        returnMap.put("product_ids", sellerStoreProductIds);
        returnMap.put("sellerId", sellerId);
        List<String> productIdList = Arrays.asList(sellerStoreProductIds.split(";"));
        ErpSellerStoreProduct erpSellerStoreProduct = new ErpSellerStoreProduct();
        ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();
        ErpSellerStoreProductExpand sellerStoreProductExpandSel = new ErpSellerStoreProductExpand();
        R<Object> objectR = null;
        for (String productId : productIdList) {
            sellerStoreProductExpandSel.setAeProductId(Long.valueOf(productId));
            objectR = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(sellerStoreProductExpandSel);
            String toJSONString = JSONObject.toJSONString(objectR.getData());
            erpSellerStoreProductExpand = JSONObject.parseObject(toJSONString, ErpSellerStoreProductExpand.class);

            if (type == 0) {
                if (!erpSellerStoreProductExpand.getProductStatusType().equals("1")) {
                    returnMap.put("product_ids", productId);
                    //下架商品
                    R<Object> objectR1 = remoteAeProductService.offlineAeProduct(returnMap);
                    if (objectR1.getCode() != 200) {
                        return objectR1;
                    }
//                    forEntity = restTemplate
//                            .postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/offlineAeProduct", returnMap, String.class);
//                    body = (String) forEntity.getBody();
                    Integer code = objectR1.getCode();
                    if (code == 200) {
//                        Integer modifyCount = JSONObject.parseObject(body).getJSONObject("msg").getJSONObject("aliexpress_postproduct_redefining_offlineaeproduct_response")
//                                .getJSONObject("result").getInteger("modify_count");
                        updateProductStatus(productId, 0);
                    } else {
                        return R.fail("下架失败");
                    }
                } else {
                    return R.fail("该商品当前状态已为下架");
                }
            } else {
                if (erpSellerStoreProductExpand.getProductStatusType().equals("1")) {
                    returnMap.put("product_ids", productId);
                    //上架商品
                    R<Object> objectR1 = remoteAeProductService.onlineAeProduct(returnMap);
                    body = (String) objectR1.getData();
//                    forEntity = restTemplate
//                            .postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/onlineaeproduct", returnMap, String.class);
//                    body = (String) forEntity.getBody();
                    Integer code = JSONObject.parseObject(body).getInteger("code");
                    if (code == 200) {
                        Integer modifyCount = JSONObject.parseObject(body).getJSONObject("msg").getJSONObject("aliexpress_postproduct_redefining_onlineaeproduct_response")
                                .getJSONObject("result").getInteger("modify_count");
                        updateProductStatus(productId, 1);
                    } else {
                        return R.fail("上架失败");
                    }
                } else {
                    return R.fail("该商品当前状态不为下架");
                }
            }
        }
        return R.ok("执行成功");

    }

    @Override
    public R<Object> deleteProductToAe(Long productId, Long sellerId) {
        Map<String, Object> returnMap = new HashMap<>();
//        if (StringUtils.isEmpty(checkSellerId(sellerId))) {
//            return R.ok("店铺未授权");
//        }
//        确认该商品是否存在
//        ErpSellerStoreProductVo erpSellerProduct = iErpSellerStoreProductService.queryById(productId);
//        if (erpSellerProduct == null) {
//            return R.ok("商品不存在");
//        }
        //Ae接口
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/deleteProduct?productId=" + productId + "&sellerId=" + sellerId, String.class);
//        String body = (String) forEntity.getBody();
//
        R<Object> objectR = remoteAeProductService.deleteProductToAe(productId, sellerId);
        String body = (String) objectR.getData();
        Integer code = objectR.getCode();
        if (code == 200) {
            return R.ok("删除商品成功");
        } else {
            return R.fail("删除商品失败");
        }
    }

    @Override
    public R<Object> queryAeProduct(Long productId, Long sellerId) {
        //访问接口，获取该店铺有无权限
        R<Object> objectR = remoteAeProductService.queryAeProduct(productId, sellerId.toString());
        String body = (String) objectR.getData();
        System.out.println(body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") == 200) {
            return R.ok(jsonObject, "获取成功");
        } else {
            return R.fail("获取失败");
        }
    }

    @Override
    public R<Object> productOfflineForUpdateTest(String sellerStoreProductIds, Long sellerId, Integer type) {
        Map<String, Object> returnMap = new HashMap<>();
        ResponseEntity<String> forEntity = null;
        String body = null;
        returnMap.put("product_ids", sellerStoreProductIds);
        returnMap.put("sellerId", sellerId);
        R<Object> objectR = remoteAeProductService.offlineAeProduct(returnMap);
        body = JSONObject.toJSONString(objectR.getData());
//        forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/offlineAeProduct", returnMap, String.class);
//        body = (String) forEntity.getBody();
        System.out.println(body);
        Integer code = objectR.getCode();
        if (code == 200) {
//            Integer modifyCount = JSONObject.parseObject(body).getJSONObject("aliexpress_postproduct_redefining_offlineaeproduct_response")
//                    .getJSONObject("result").getInteger("modify_count");
            return R.ok("下架成功");
        } else {
            return R.fail("下架失败");
        }
    }

    public void updateProductStatus(String productId, Integer type) {
        ErpSellerStoreProduct erpSellerStoreProduct = new ErpSellerStoreProduct();
        ErpCollectProductExpand erpCollectProductExpand = new ErpCollectProductExpand();
        erpSellerStoreProduct = erpSellerStoreProductMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreProduct>().eq(ErpSellerStoreProduct::getAeProductId, productId)
        );
        R<Object> objectR = null;

        if (erpSellerStoreProduct != null) {
            ErpSellerStoreProductExpand sellerStoreProductExpandSel = new ErpSellerStoreProductExpand();
            sellerStoreProductExpandSel.setSellerStoreProductId(erpSellerStoreProduct.getId());
            objectR = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(sellerStoreProductExpandSel);
            String toJSONString = JSONObject.toJSONString(objectR.getData());
            ErpSellerStoreProductExpand erpSellerStoreProductExpand = JSONObject.parseObject(toJSONString, ErpSellerStoreProductExpand.class);
            if (type == 0) {
                erpSellerStoreProductExpand.setProductStatusType("1");
            } else {
                erpSellerStoreProductExpand.setProductStatusType("0");
            }
            remoteSellerStoreProductService.updateErpSellerStoreProductExpand(erpSellerStoreProductExpand);
        }

    }


    @Override
    public R<Object> disposeProductData(Long sellerStoreProductId, Long sellerId, Integer postType) {
        Map<String, Object> returnMap = new HashMap<>();

        returnMap.put("sellerId", sellerId);

        // 获取店铺延伸表，获取其中的报价币种
        ErpSellerStoreEmpowerExtend storeExtendSel = new ErpSellerStoreEmpowerExtend();
        storeExtendSel.setSellerId(sellerId);
        storeExtendSel.setType(1);
        R<Object> storeExtendObject = remoteSellerStoreService.getSellerStoreExtendInfo(storeExtendSel);
        String storeExtendString = JSONObject.toJSONString(storeExtendObject.getData());
        ErpSellerStoreEmpowerExtend erpSellerStoreEmpowerExtend = JSONObject.parseObject(storeExtendString, ErpSellerStoreEmpowerExtend.class);


        if (erpSellerStoreEmpowerExtend == null) {
            return R.fail("店铺资质信息异常");
        }
        // 上传图片至图片银行
        R<Object> allPicByProductId = getAllPicByProductId(sellerStoreProductId);
        if (allPicByProductId.getCode() != 200) {
            return R.fail(allPicByProductId.getMsg().toString());
        }

        // 获取信息
        returnMap = postProductToAe(erpSellerStoreEmpowerExtend, sellerStoreProductId, sellerId, postType);
        if (returnMap.get("code").equals(501)) {
            return R.fail("店铺没有该分类商品的发布权限");
        } else if (returnMap.get("code").equals(502)) {
            return R.fail("该商品已不存在于平台");
        }


        // 调用Ae接口
//        String returnUrl = aeConfig.getEndpoint() + "/erp/erpProduct/getErpProductInfo";
//        ResponseEntity<String> forEntity = restTemplate.postForEntity(returnUrl, aeProductPost, String.class);
        AeProductPost aeProductPost = (AeProductPost) returnMap.get("aeProduct");
        aeProductPost.setSellerId(sellerId);
        System.out.println(returnMap.get("aeProduct"));
        System.out.println(aeProductPost.toString());
        String s = JSON.toJSONString(aeProductPost);
        System.out.println(s);
        R<Object> objectR = remoteAeProductService.getErpProductInfo(aeProductPost);
        String msg = (String) objectR.getMsg();
        String data = (String) objectR.getData();
        System.out.println(data);
//        String code = JSONObject.parseObject(body).getString("code");
        Integer code = objectR.getCode();
        if (code != 200) {
            // 分析返回请求
            String errorCode = JSONObject.parseObject(data).getJSONObject("error_response")
                    .getString("sub_code");
            if (errorCode != null) {
                // 查找错误编码确认对应错误
                AeProductPostError error = iAeProductPostErrorService.selectByErrorCode(errorCode);
                if (error != null) {
                    return R.fail(error.getErrorReason());
                } else {
                    String sub_msg = JSONObject.parseObject(data).getJSONObject("error_response")
                            .getString("sub_msg");
                    return R.fail(sub_msg);
                }
            } else {
                return R.fail(JSONObject.parseObject(data).getJSONObject("error_response").getString("msg"));
            }
        } else {
            String productId = JSONObject.parseObject(data)
                    .getJSONObject("aliexpress_offer_product_post_response").getJSONObject("result")
                    .getString("product_id");
            // 新增商品成功
            ErpSellerStoreProduct erpSellerStoreProduct = erpSellerStoreProductMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreProduct>().eq(ErpSellerStoreProduct::getId, sellerStoreProductId));
            erpSellerStoreProduct.setAeProductId(Long.valueOf(productId));
            erpSellerStoreProductMapper.updateById(erpSellerStoreProduct);


            ErpSellerStoreProductExpand erpSellerStoreProductExpandSel = new ErpSellerStoreProductExpand();
            erpSellerStoreProductExpandSel.setSellerStoreProductId(erpSellerStoreProduct.getId());
            R<Object> erpSellerStoreProductExpandObject = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(erpSellerStoreProductExpandSel);
            String erpSellerStoreProductExpandString = JSONObject.toJSONString(erpSellerStoreProductExpandObject.getData());
            ErpSellerStoreProductExpand erpSellerStoreProductExpand = JSONObject.parseObject(erpSellerStoreProductExpandString, ErpSellerStoreProductExpand.class);
            erpSellerStoreProductExpand.setAeProductId(Long.valueOf(productId));
            remoteSellerStoreProductService.updateErpSellerStoreProductExpand(erpSellerStoreProductExpand);


            //            postAddProductId(sellerStoreProductId, Long.valueOf(productId));
            return R.ok("上传成功");
        }

    }

    /**
     * 图片银行
     *
     * @param productId
     * @return
     */
    @Override
    @Transactional
    public R<Object> getAllPicByProductId(Long productId) {
        ErpSellerStoreProduct sellerStoreProduct = erpSellerStoreProductMapper.selectById(productId);

        ErpSellerStoreProductExpand sellerStoreProductExtendSel = new ErpSellerStoreProductExpand();
        sellerStoreProductExtendSel.setSellerStoreProductId(productId);
        R<Object> sellerStoreProductExtendSelObject = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(sellerStoreProductExtendSel);
        String sellerStoreProductExtendString = JSONObject.toJSONString(sellerStoreProductExtendSelObject.getData());
        ErpSellerStoreProductExpand sellerStoreProductExpand = JSONObject.parseObject(sellerStoreProductExtendString, ErpSellerStoreProductExpand.class);

//        ErpSellerStoreProductExpand sellerStoreProductExpand = erpSellerStoreProductExpandMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
//                        .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, productId)
//        );

        if (sellerStoreProduct == null || sellerStoreProductExpand == null) {
            return R.fail("商品不存在");
        }
        Integer isAddWatemark = sellerStoreProductExpand.getIsAddWatemark();
        Long storeId = sellerStoreProduct.getStoreId();
        List<ImageBankParam> bankParamList = new ArrayList<>();
        // 1.查询商品的所有图片
        R<Object> sellerStoreInfoObject = remoteSellerStoreService.getSellerStoreInfoById(storeId);
        String sellerStoreInfoString = JSONObject.toJSONString(sellerStoreInfoObject.getData());
        ErpSellerStoreEmpower erpSellerStoreEmpowerExtend = JSONObject.parseObject(sellerStoreInfoString, ErpSellerStoreEmpower.class);
        String storeUserName = erpSellerStoreEmpowerExtend.getStoreUserName();
        // 主图
        String imageURLs = sellerStoreProduct.getImageURLs();
        if (StringUtils.isNotEmpty(imageURLs)) {
            List<String> imageURLList = ListUtil.toList(imageURLs.split(";"));
            for (String s : imageURLList) {
                if (s.startsWith("http://") || s.startsWith("https://"))
                    continue;
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setType(0);
                bankParam.setImageUrl(s);
                bankParamList.add(bankParam);
            }
        }
        // 白底图
        String white = sellerStoreProduct.getWhite();
        if (StringUtils.isNotEmpty(white)) {
            List<String> whiteList = ListUtil.toList(white.split(";"));
            for (String s : whiteList) {
                if (s.startsWith("http://") || s.startsWith("https://"))
                    continue;
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setImageUrl(s);
                bankParam.setType(1);
                bankParamList.add(bankParam);
            }
        }
        // 营销图
        String marketing = sellerStoreProduct.getMarketing();
        if (StringUtils.isNotEmpty(marketing)) {
            List<String> markList = ListUtil.toList(marketing.split(";"));
            for (String s : markList) {
                if (s.startsWith("http://") || s.startsWith("https://"))
                    continue;
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setImageUrl(s);
                bankParam.setType(2);
                bankParamList.add(bankParam);
            }
        }
        // 详情图
        String detailImg = null;
        detailImg = sellerStoreProduct.getDetailImg();
        if (StringUtils.isNotEmpty(detailImg)) {
            List<String> detailImgList = ListUtil.toList(detailImg.split(";"));
            for (String s : detailImgList) {
                if (s.startsWith("http://ae01.alicdn") || s.startsWith("https://ae01.alicdn"))
                    continue;
                ImageBankParam bankParam = new ImageBankParam();
                bankParam.setImageUrl(s);
                bankParam.setType(3);
                bankParamList.add(bankParam);
            }
        }
        // sku图集
        List<ErpSellerStoreProductSku> sellerStoreProductSkuList = erpSellerStoreProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
                        .eq(ErpSellerStoreProductSku::getSellerStoreProductId, productId));
        for (ErpSellerStoreProductSku sku : sellerStoreProductSkuList) {
            // sku主图
            String skuImage = sku.getSkuImage();
            if (StringUtils.isNotEmpty(skuImage)) {
                List<String> skuImageList = ListUtil.toList(skuImage.split(";"));
                for (String s : skuImageList) {
                    ImageBankParam bankParam = new ImageBankParam();
                    bankParam.setImageUrl(s);
                    bankParam.setSkuCode(sku.getSkuCode());
                    bankParam.setType(4);
                    bankParamList.add(bankParam);
                }
            }
        }

        bankParamList.forEach(
                param -> {
                    param.setProductId(productId);
                    param.setGroupId("0");
                    param.setSellerId(storeId);
                    param.setStoreUserName(storeUserName);
                    param.setIsAddWatemark(isAddWatemark);
                }
        );

        // 2. 将图片传给ae,获取返回的新图
        RestTemplate restTemplate = new RestTemplate();
        String body = null;
        ResponseEntity<String> forEntity = null;
        List<ImageBankParam> returnList = new ArrayList<>();
        for (ImageBankParam imageBankParam : bankParamList) {
            R<Object> imageBankParamObject = remoteAeProductService.uploadImageForSDKTest(imageBankParam);
            String imageBankParamString = JSONObject.toJSONString(imageBankParamObject.getData());
            ImageBankParam imageBankParam1 = JSONObject.parseObject(imageBankParamString, ImageBankParam.class);
            System.out.println(imageBankParam1);
            returnList.add(imageBankParam1);
        }
        List<String> errorList = new ArrayList<>();
        for (ImageBankParam imageBankParam : returnList) {
            Long id = imageBankParam.getProductId();
            String newDraw = imageBankParam.getNewDraw();
            String imageUrl = imageBankParam.getImageUrl();
            Integer type = imageBankParam.getType(); // type=4,id表示sku表的主键,其余表示商品表主键
            if (newDraw == null) {
                errorList.add(imageUrl);
                continue;
            }
            if (newDraw.equals("continue")) {
                errorList.add(imageUrl);
                continue;
            }
            switch (type) {
                case 0:
                    imageURLs = imageURLs.replace(imageUrl, newDraw);
                    break;
                case 1:
                    white = white.replace(imageUrl, newDraw);
                    break;
                case 2:
                    marketing = marketing.replace(imageUrl, newDraw);
                    break;
                case 3:
                    detailImg = detailImg.replace(imageUrl, newDraw);
                    break;
                case 4:
                    ErpSellerStoreProductSku sku = erpSellerStoreProductSkuMapper.selectOne(
                            new LambdaQueryWrapper<ErpSellerStoreProductSku>()
                                    .eq(ErpSellerStoreProductSku::getSellerStoreProductId, id)
                                    .eq(ErpSellerStoreProductSku::getSkuCode, imageBankParam.getSkuCode())
                    );
                    // 获取skuproperty
                    sku.setSkuProperty(sku.getSkuProperty().replace(sku.getSkuImage(), newDraw));
                    sku.setSkuImage(newDraw);
                    erpSellerStoreProductSkuMapper.updateById(sku);
                    break;
            }
        }

        if (errorList.size() > 0) {
            return R.fail("异常图片" + errorList);
        }

        sellerStoreProduct.setImageURLs(imageURLs);
        sellerStoreProduct.setMarketing(marketing);
        sellerStoreProduct.setDetailImg(detailImg);
        sellerStoreProduct.setWhite(white);
        erpSellerStoreProductMapper.updateById(sellerStoreProduct);
        return R.ok("上传成功");
    }


    /**
     * 发送产品至Ae
     *
     * @param sellerStoreProductId
     * @return
     */
    @Override
    public Map<String, Object> postProductToAe(ErpSellerStoreEmpowerExtend erpSellerStoreEmpowerExtend,
                                               Long sellerStoreProductId, Long sellerId,
                                               Integer postType) {
        //postType 1-商品新增 2-商品信息普通修改 3-商品资质信息上传 4-商品调价 5-2.0商品同步信息 6-商品不良信息优化 7-自动化上品
        AeProductPost aeProduct = new AeProductPost();
        Map<String, Object> returnMap = new HashMap<>();
        aeProduct.setPostType(postType);
        aeProduct.setSellerId(sellerId);
        returnMap.put("aeProduct", aeProduct);
        //币种 与店铺相关
        aeProduct.setCurrency_code(erpSellerStoreEmpowerExtend.getQuotationCurrency());

        ErpSellerStoreProduct sellerStoreProduct = erpSellerStoreProductMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreProduct>().eq(ErpSellerStoreProduct::getId, sellerStoreProductId));

        //取公共采集表中数据
        ErpCollectProduct erpCollectProduct = erpCollectProductMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProduct>().eq(ErpCollectProduct::getId, sellerStoreProduct.getCollectProductId())
        );

        // 查看该店铺是否拥有该分类发布权限
        if (!checkStoreSubCategory(erpCollectProduct, aeProduct.getSellerId())) {
            // 返回false，判断true
            returnMap.put("code", 501);
            return returnMap;
        }

//        //获取资质信息 //TODO 暂不使用
//        if (true) {
//            //获取该商品所在的方案
//            ErpCollectProductQualificationProgram program = erpCollectProductQualificationProgramMapper.selectOne(
//                    new LambdaQueryWrapper<ErpCollectProductQualificationProgram>()
//                            .like(ErpCollectProductQualificationProgram::getCollectProductId, erpCollectProduct.getId())
//            );
//            if (ObjectUtils.isNotEmpty(program)) {
//                JSONArray jsonArray = JSONArray.parseArray(program.getDetails());
//
//                List<Map<String, Object>> mapList = new ArrayList<>();
//                Map<String, Object> map = new HashMap<>();
//
//                for (int i = 0; i < jsonArray.size(); i++) {
//                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    if (jsonObject.getString("value").equals("")) {
//                        continue;
//                    }
//                    String value = "https://file.pbb2c.com/" + jsonObject.getString("value");
////                    jsonObject.put("value", value);
//                    map.put(jsonObject.getString("key"), value);
//                }
//
//
//                //查找现在当前分类所需的最新资质
//                R<Object> objectR = queryCategoryQualificationList(sellerStoreProduct.getCategoryId());
//                if (ObjectUtils.isNotEmpty(objectR.getData())) {
//                    //若不为空，则进行比对
//                    List<ErpCollectProductCategoryQualification> qualifications = (List<ErpCollectProductCategoryQualification>) objectR.getData();
//                    for (ErpCollectProductCategoryQualification qualification : qualifications) {
//                        if (ObjectUtils.isNotEmpty(map.get(qualification.getQualificationKey()))) {
//                            Map<String, Object> qualificationMap = new HashMap<>();
//                            qualificationMap.put("key", qualification.getQualificationKey());
//                            qualificationMap.put("value", map.get(qualification.getQualificationKey()));
//                            mapList.add(qualificationMap);
//                        }
//
//                    }
//                }
//
//                ObjectMapper objectMapper = new ObjectMapper();
//
//                // 使用writeValueAsString()方法将List转换为JSON字符串
//                String json = null;
//                try {
//                    json = objectMapper.writeValueAsString(mapList);
//                } catch (JsonProcessingException e) {
//                    e.printStackTrace();
//                }
//
//                aeProduct.setAeop_qualification_struct_list(json);
//            }
//        }


        //获取公共采集产品库信息
        returnMap = getErpCollectProductInfo(sellerStoreProduct, erpCollectProduct, returnMap);
        if (!returnMap.get("code").equals(200)) {
            return returnMap;
        }

        // 获取在线产品库产品信息
        returnMap = getErpSellerStoreProductInfo(sellerStoreProduct, returnMap);
        if (!returnMap.get("code").equals(200)) {
            return returnMap;
        }

        //取公共产品库延伸表中数据
        ErpCollectProductExpand collectProductExpandSel = new ErpCollectProductExpand();
        collectProductExpandSel.setCollectProductId(sellerStoreProduct.getCollectProductId());
        R<Object> collectProductExpandInfoObject = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpandSel);
        String collectProductExpandInfoString = JSONObject.toJSONString(collectProductExpandInfoObject.getData());
        ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(collectProductExpandInfoString, ErpCollectProductExpand.class);
        returnMap = getErpCollectProductExpandInfo(collectProductExpand, returnMap);
        if (!returnMap.get("code").equals(200)) {
            return returnMap;
        }

        // 取在线商品表延伸表中数据
//        ErpSellerStoreProductExpand erpSellerStoreProductExpand = erpSellerStoreProductExpandMapper
//                .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
//                        .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId));

        ErpSellerStoreProductExpand erpSellerStoreProductExpandSel = new ErpSellerStoreProductExpand();
        erpSellerStoreProductExpandSel.setSellerStoreProductId(sellerStoreProductId);
        R<Object> erpSellerStoreProductExpandObject = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(erpSellerStoreProductExpandSel);
        String erpSellerStoreProductExpandString = JSONObject.toJSONString(erpSellerStoreProductExpandObject.getData());
        ErpSellerStoreProductExpand erpSellerStoreProductExpand = JSONObject.parseObject(erpSellerStoreProductExpandString, ErpSellerStoreProductExpand.class);
        returnMap = getErpSellerStoreProductExpandInfo(erpSellerStoreEmpowerExtend, erpSellerStoreProductExpand, returnMap);
        if (!returnMap.get("code").equals(200)) {
            return returnMap;
        }

        // 欧盟负责人判别
        Integer type = 1;
        if (erpSellerStoreProductExpand.getRemark() != null) {
            if (erpSellerStoreProductExpand.getRemark().contains("Invalid msr eu")) {
                type = 0;
            }
        }
        String euResponsiblePersonByCategoryId = getEUResponsiblePersonByCategoryId(
                erpCollectProduct.getCategoryId(), sellerId, type);
        if (euResponsiblePersonByCategoryId != null) {
            aeProduct.setMsr_eu_id(euResponsiblePersonByCategoryId);
        }


        // 取ERP_SELLER_Store_PRODUCT_SKU表中数据
        ErpSellerStoreProductSku erpSellerStoreProductSkuSel = new ErpSellerStoreProductSku();
        erpSellerStoreProductSkuSel.setSellerStoreProductId(sellerStoreProductId);
        R<Object> erpSellerStoreProductSkuSelObject = remoteSellerStoreProductService.getSellerStoreProductSkuListInfo(erpSellerStoreProductSkuSel);
        String erpSellerStoreProductSkuSelString = JSONObject.toJSONString(erpSellerStoreProductSkuSelObject.getData());
        List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = JSONArray.parseArray(erpSellerStoreProductSkuSelString, ErpSellerStoreProductSku.class);
        returnMap = getErpSellerProductSKUInfo(erpSellerStoreEmpowerExtend, erpSellerStoreProductSkuList, returnMap, aeProduct, sellerStoreProduct);
        if (!returnMap.get("code").equals(200)) {
            return returnMap;
        }
        return returnMap;
    }

    /**
     * 查验店铺的一级分类
     *
     * @param erpCollectProduct
     * @param storeId
     * @return
     */
    @Override
    public Boolean checkStoreSubCategory(ErpCollectProduct erpCollectProduct, Long storeId) {
        Long categoryId = null;
        ErpCollectProductCategory erpCollectProductCategory = erpCollectProductCategoryMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProductCategory>().eq(ErpCollectProductCategory::getId,
                        erpCollectProduct.getCategoryId()));
        if (erpCollectProductCategory != null) {
            if (erpCollectProductCategory.getParentId() == 0) {
                // 顶点
                categoryId = erpCollectProductCategory.getId();
            } else {
                // 非顶点
                // 转为数组，获取第数组的第二个对象
                String[] ancestors = erpCollectProductCategory.getAncestors().split(",");
                categoryId = Long.valueOf(ancestors[1]);
            }
        } else {
            return false;
        }

        R<Object> subCategoryObject = remoteSellerStoreService.getSubcategoryByStoreIdAndCategoryId(storeId, categoryId);
        String subCategoryString = JSONObject.toJSONString(subCategoryObject.getData());
        ErpSellerStoreSubcategory erpSellerStoreSubcategories = JSONObject.parseObject(subCategoryString, ErpSellerStoreSubcategory.class);
        if (erpSellerStoreSubcategories != null) {
            return true;
        } else {
            return false;
        }

    }


    private Map<String, Object> getErpCollectProductInfo(ErpSellerStoreProduct sellerStoreProduct, ErpCollectProduct erpCollectProduct, Map<String, Object> returnMap) {
        AeProductPost aeProduct = (AeProductPost) returnMap.get("aeProduct");
        // 该商品的一级分类
        aeProduct.setCategory_id(erpCollectProduct.getCategoryId());

        // 产品属性
        // 处理产品属性
        // 取在线商品表中的产品属性
        JSONArray sellerStoreProductCustomAttributes = JSONArray.parseArray(sellerStoreProduct.getCustomAttributes());
        JSONArray collectProductCustomAttributes = JSONArray.parseArray(erpCollectProduct.getCustomAttributes());
        collectProductCustomAttributes.add(0, sellerStoreProductCustomAttributes.get(0));

        List<AeProductPost.AeopAeProductPropertys> customAttributeList = JSONArray
                .parseArray(collectProductCustomAttributes.toJSONString(), AeProductPost.AeopAeProductPropertys.class);

        aeProduct.setAeop_ae_product_propertys(customAttributeList);

        Double grossWeight = Double.valueOf(erpCollectProduct.getGrossWeight()) / 1000;
        aeProduct.setGross_weight(grossWeight.toString());
        aeProduct.setPackage_height(erpCollectProduct.getPackageHeight().intValue());
        aeProduct.setPackage_length(erpCollectProduct.getPackageLength().intValue());
        aeProduct.setPackage_width(Integer.valueOf(erpCollectProduct.getPackageWidth()));
        aeProduct.setProduct_unit(erpCollectProduct.getProductUnit());
        aeProduct.setSizechart_id(erpCollectProduct.getSizechartId());
        aeProduct.setProduct_price(erpCollectProduct.getProductPrice());
        aeProduct.setCollectProductId(erpCollectProduct.getId());
        returnMap.put("code", 200);
        returnMap.put("aeProduct", aeProduct);
        return returnMap;
    }

    /**
     * 获取 ErpSellerStoreProduct 表中信息
     *
     * @param erpSellerStoreProduct
     * @param returnMap
     * @return
     */
    private Map<String, Object> getErpSellerStoreProductInfo(ErpSellerStoreProduct erpSellerStoreProduct,
                                                             Map<String, Object> returnMap) {
        AeProductPost aeProduct = (AeProductPost) returnMap.get("aeProduct");
        if (erpSellerStoreProduct == null) {
            returnMap.put("code", 500);
        } else {
            // 商品详描
            List<AeProductPost.DetailSourceList> detailSourceList = new ArrayList<>();
            AeProductPost.DetailSourceList detailSource = new AeProductPost.DetailSourceList();
//            ErpCollectProduct collectProduct = erpCollectProductMapper.selectById(
//                    new LambdaQueryWrapper<ErpCollectProduct>()
//                            .select(ErpCollectProduct::getOldDetailImg)
//                            .eq(ErpCollectProduct::getId, erpSellerStoreProduct.getCollectProductId())
//            );
            String makeDetail = null;
//            if (ObjectUtils.isNull(collectProduct.getOldDetailImg())) {
            makeDetail = makeDetail(erpSellerStoreProduct.getDetail(), erpSellerStoreProduct.getDetailImg());
//            } else {
//                makeDetail = makeDetail(erpSellerStoreProduct.getDetail(), collectProduct.getOldDetailImg());
//            }
            detailSource.setMobile_detail(makeDetail);
            detailSource.setWeb_detail(makeDetail);
            detailSource.setLocale("en_US");
            detailSourceList.add(detailSource);
            aeProduct.setDetail_source_list(detailSourceList);

            // 商品标题
            AeProductPost.ErpProductSubject subject = new AeProductPost.ErpProductSubject();
            subject.setLocale("en_US");

            subject.setValue(erpSellerStoreProduct.getSubject());

            List<AeProductPost.ErpProductSubject> subjectList = new ArrayList<>();
            subjectList.add(subject);
            aeProduct.setSubject_list(subjectList);

            //营销图和白底图
            List<AeProductPost.MarketImages> marketImagesList = new ArrayList<>();
            // 营销图
            if (ObjectUtils.isNotEmpty(erpSellerStoreProduct.getMarketing())) {
                AeProductPost.MarketImages marketImages = new AeProductPost.MarketImages();
                marketImages.setUrl(erpSellerStoreProduct.getMarketing());
                marketImages.setImage_type(1);
                marketImagesList.add(marketImages);
            }
            // 白底图
            if (ObjectUtils.isNotEmpty(erpSellerStoreProduct.getWhite())) {
                AeProductPost.MarketImages whiteImages = new AeProductPost.MarketImages();
                whiteImages.setUrl(erpSellerStoreProduct.getWhite());
                whiteImages.setImage_type(2);
                marketImagesList.add(whiteImages);
            }
            aeProduct.setMarket_images(marketImagesList);

            //轮播图
            aeProduct.setImage_u_r_ls(erpSellerStoreProduct.getImageURLs());

            returnMap.put("code", 200);
            returnMap.put("aeProduct", aeProduct);
        }
        return returnMap;
    }

    /**
     * 商品详描处理
     *
     * @param detail
     * @param imgUrls
     * @return
     */
    public String makeDetail(String detail, String imgUrls) {
        Map<String, Object> map = new HashMap<>();
        map.put("version", "2.0.0");
        Map<String, Object> map1 = new LinkedMap<String, Object>();
        map1.put("type", "text-image");

        // 文本
        List<Object> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(detail)) {
            String[] split = detail.split("\n");
            for (String string : split) {
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("content", string);
                map2.put("class", "body");
                list.add(map2);
            }
        }

        // 图片
        List<Object> list2 = new LinkedList<>();
        String[] split2 = imgUrls.split(";");
        for (String string : split2) {
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("url", string);
            map2.put("style", new HashMap<>());
            list2.add(map2);
        }

        if (list != null && list.size() != 0)
            map1.put("texts", list);
        if (list2 != null && list2.size() != 0)
            map1.put("images", list2);
        List<Object> resList = new ArrayList<Object>();
        resList.add(map1);
        map.put("moduleList", resList);
        return JsonUtils.toJsonString(map);
    }

    /**
     * 获取公共产品延伸表中需要数据
     *
     * @param collectProductExpand
     * @param returnMap
     * @return
     */
    private Map<String, Object> getErpCollectProductExpandInfo(
            ErpCollectProductExpand collectProductExpand,
            Map<String, Object> returnMap) {
        AeProductPost aeProduct = (AeProductPost) returnMap.get("aeProduct");
        if (collectProductExpand == null) {
            returnMap.put("code", 502);
        } else {
            //批发最小数量
            aeProduct.setBulk_order(collectProductExpand.getBulkOrder());
            // 批发折扣
            aeProduct.setBulk_discount(collectProductExpand.getBulkDiscount());
            // 每包件数
            aeProduct.setLot_num(collectProductExpand.getLotNum());
            //购买几件以内不增加运费。取值范围1-1000
            aeProduct.setBase_unit(collectProductExpand.getBaseUnit());

            //每增加件数
            aeProduct.setAdd_unit(collectProductExpand.getAddUnit());
            //对应增加的重量
            aeProduct.setAdd_weight(collectProductExpand.getAddWeight());
            //备货期
            aeProduct.setDelivery_time(collectProductExpand.getDeliveryTime());
            //打包銷售
            aeProduct.setPackage_type(collectProductExpand.getPackageType());
            //是否自定义计重
            aeProduct.setIs_pack_sell(collectProductExpand.getIsPackSell());

            //是否是2.0的品
            if (ObjectUtils.isNotNull(collectProductExpand) && collectProductExpand.getClassifyLabel().contains("1719179918137212929")) {
                aeProduct.setProductType(0);
            } else {
                aeProduct.setProductType(1);
            }
            returnMap.put("code", 200);
            returnMap.put("aeProduct", aeProduct);
        }
        return returnMap;
    }

    /**
     * 处理获取ErpSellerStoreProductExpand表中数据
     *
     * @param erpSellerStoreProductExpand
     * @param returnMap
     * @return
     */
    private Map<String, Object> getErpSellerStoreProductExpandInfo(
            ErpSellerStoreEmpowerExtend erpSellerStoreEmpowerExtend,
            ErpSellerStoreProductExpand erpSellerStoreProductExpand, Map<String, Object> returnMap) {
        AeProductPost aeProduct = (AeProductPost) returnMap.get("aeProduct");
        if (erpSellerStoreProductExpand == null) {
            returnMap.put("code", 500);
        } else {

            if (ObjectUtils.isNotNull(erpSellerStoreProductExpand.getIsMainImageReordering()) && erpSellerStoreProductExpand.getIsMainImageReordering() == 1) {
                ErpSellerStoreProduct sellerStoreProduct = erpSellerStoreProductMapper.selectById(erpSellerStoreProductExpand.getSellerStoreProductId());
                String imageURLs = sellerStoreProduct.getImageURLs();
                //主图调序
                List<String> imageNewList = Arrays.asList(imageURLs.split(";"));
                if (imageNewList.size() > 2) {
                    //有两张以上时调序
                    //获取第一张
                    String imageOne = imageNewList.get(0);
                    //获取除第一张的其他List
                    List<String> otherElements = imageNewList.subList(1, imageNewList.size());
                    Collections.shuffle(otherElements);
//                    otherElements.add(0     ,imageOne);
                    String imageNewUrl = imageOne + ";" + StringUtils.join(otherElements, ";");
                    System.out.println(imageNewUrl);
                }
            }

            //分组策略
            aeProduct.setGroup_id(erpSellerStoreProductExpand.getGroupId());
            //服务模板
            aeProduct.setPromis_template_id(erpSellerStoreProductExpand.getPromiseTemplateId());
            //库存扣减策略
            aeProduct.setReduce_strategy(erpSellerStoreProductExpand.getReduceStrategy());
            //商品有效天数。取值范围:1-7,单位:天。
            aeProduct.setWs_valid_num(erpSellerStoreProductExpand.getWsValidNum());
//            aeProduct.setEan_code(erpSellerStoreProductExpand.getEanCode());

            // 区域定价
            String absoluteQuoteMapStr = erpSellerStoreProductExpand.getAbsoluteQuoteMap();
            if (ObjectUtils.isNotEmpty(absoluteQuoteMapStr)) {
                List<Dict> absoluteQuoteMapList = JsonUtils
                        .parseArrayMap(erpSellerStoreProductExpand.getAbsoluteQuoteMap());
                // 获取运费，换算金额
                BigDecimal newUsdExchange = iErpUsdExchangeService.getNewUsdExchange();
                for (Dict dict : absoluteQuoteMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                        // 换算价格
                        if (erpSellerStoreEmpowerExtend.getQuotationCurrency().equals("USD")) {
                            BigDecimal res = amount.multiply(BigDecimal.valueOf(100)).divide(newUsdExchange,
                                    BigDecimal.ROUND_CEILING);
                            absoluteQuoteMap.put(key, res.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        } else {
                            absoluteQuoteMap.put(key, amount.doubleValue());
                        }
                        // 只保留两位小数
                    }
                }
                // 获取完成的区域定价
                absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);
                aeProduct.setAeop_national_quote_configuration(absoluteQuoteMapStr);
            }

            //运费模板
            aeProduct.setFreight_template_id(erpSellerStoreProductExpand.getFreightTemplateId());
            //查看是否有海外仓
            if (ObjectUtils.isNotEmpty(erpSellerStoreProductExpand.getOverseasWarehouse())) {
                aeProduct.setShipsFromCountry(erpSellerStoreProductExpand.getOverseasWarehouse());
            } else {
                aeProduct.setShipsFromCountry(null);
            }

            returnMap.put("code", 200);
            returnMap.put("aeProduct", aeProduct);
        }
        return returnMap;
    }

    /**
     * 获取SKU相关信息
     *
     * @param erpSellerStoreEmpowerExtend
     * @param erpSellerStoreProductSkuList
     * @param returnMap
     * @param aeProduct
     * @return
     */
    private Map<String, Object> getErpSellerProductSKUInfo(ErpSellerStoreEmpowerExtend erpSellerStoreEmpowerExtend,
                                                           List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList,
                                                           Map<String, Object> returnMap,
                                                           AeProductPost aeProduct,
                                                           ErpSellerStoreProduct sellerStoreProduct) {
        aeProduct = (AeProductPost) returnMap.get("aeProduct");
        returnMap.put("code", 200);
        // 创造必要变量
        List<AeProductPost.AeopAeProductSKUs> aeSkuList = new ArrayList<>();
        AeProductPost.AeopAeProductSKUs aeSku = new AeProductPost.AeopAeProductSKUs();
        BigDecimal newUsdExchange = iErpUsdExchangeService.getNewUsdExchange();
        // 进入循环
        if (erpSellerStoreProductSkuList.size() != 0) {
            List<AeProductPost.SkuNationalDiscountPrice> skuNationalDiscountPrice = new ArrayList<>();
            AeProductPost.SkuNationalDiscountPrice discountPrice = new AeProductPost.SkuNationalDiscountPrice();
            List<AeProductPost.AeopSKUProperty> aeopSKUPropertyList = new ArrayList<>();
            AeProductPost.AeopSKUProperty skuProperty = new AeProductPost.AeopSKUProperty();
            for (ErpSellerStoreProductSku sellerSku : erpSellerStoreProductSkuList) {
                if (sellerSku.getDelFlag().equals("1")) {
                    continue;
                }
                aeSku = new AeProductPost.AeopAeProductSKUs();

                //在线商品表的sku
                aeSku.setSku_code(sellerSku.getSkuCode());
                aeSku.setSku_discount_price(sellerSku.getSkuDiscountPrice());
                aeSku.setCurrency_code(erpSellerStoreEmpowerExtend.getQuotationCurrency());
                // 换算价格
                //如果店铺是USD账户，则进行换算，如果不是则不换算
                BigDecimal skuConversionPrice = BigDecimal.valueOf(0);
                if (erpSellerStoreEmpowerExtend.getQuotationCurrency().equals("USD")) {
                    skuConversionPrice = BigDecimal.valueOf(Double.valueOf(sellerSku.getSkuPrice()))
                            .multiply(BigDecimal.valueOf(100)).divide(newUsdExchange, BigDecimal.ROUND_CEILING);
                    aeSku.setSku_price(skuConversionPrice.toString());
                } else {
                    aeSku.setSku_price(sellerSku.getSkuPrice());
                }

                // 获取SKU采集表对应值

                ErpCollectProductSku erpCollectProductSkuSel = new ErpCollectProductSku();
                erpCollectProductSkuSel.setCollectProductId(sellerStoreProduct.getCollectProductId());
                erpCollectProductSkuSel.setSkuCode(sellerSku.getSkuCode());
                R<Object> collectProductSkuObject =  remoteCollectProductService.getCollectProductSkuInfo(erpCollectProductSkuSel);
                String collectProductSkuString = JSONObject.toJSONString(collectProductSkuObject.getData());
                ErpCollectProductSku collectSku = JSONObject.parseObject(collectProductSkuString, ErpCollectProductSku.class);

                if (ObjectUtil.isNull(collectSku)) {
                    continue;
                }
                aeSku.setGross_weight(collectSku.getSkuWeight().toString());
                aeSku.setPackage_height(collectSku.getSkuHeight().intValue());
                aeSku.setPackage_width(collectSku.getSkuWidth().intValue());
                aeSku.setPackage_length(collectSku.getSkuLength().intValue());
                aeSku.setIpm_sku_stock(sellerSku.getSkuStock());
                if (sellerSku.getSkuStock() > 0) {
                    aeSku.setSku_stock("true");
                } else {
                    aeSku.setSku_stock("false");
                }


                // 直接转换
                List<AeProductPost.AeopSKUProperty> skuPropertyList = JSONArray.parseArray(sellerSku.getSkuProperty(),
                        AeProductPost.AeopSKUProperty.class);
                aeSku.setAeop_s_k_u_property(skuPropertyList);
                aeSku.setId(sellerSku.getSkuPropertyIds());
                aeSkuList.add(aeSku);
            }
            aeProduct.setAeop_ae_product_s_k_us(aeSkuList);
            returnMap.put("aeProduct", aeProduct);
        }
        return returnMap;

    }





}
